<?php
namespace App\Http\Controllers\Client\Shop\Explore;

use App\Http\Controllers\ClientController;
use App\Jobs\ExploreApplyJob;
use App\Models\Common\File;
use App\Models\Tools\Data;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ExploreApplyController extends ClientController
{

    public function index()
    {

        $all = $this->all;

        // 验证参数
        try {
            if (!isset($all['shop_id'])) {
                throw new \Exception('缺少参数:shop_id');
            }
            if (!isset($all['channel_id'])) {
                throw new \Exception('缺少参数:channel_id');
            }
            if (!isset($all['num'])) {
                throw new \Exception('缺少参数:num');
            }
            if (!isset($all['date'])) {
                throw new \Exception('缺少参数:date');
            }
            if (count($all['date'])!==2) {
                throw new \Exception('参数:date格式错误');
            }
        }catch (\Exception $e) {
            Log::error(ExploreApplyController::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1, '参数错误');
        }

        $shop_id = $all['shop_id'];
        $channel_id = $all['channel_id'];
        $num = $all['num'];
        $date = $all['date'];
        $remark = $all['remark']??'';
        $offline = $all['offline'] ?1 :0;

        try{
            // 检查当前店铺状态
            $verified = DB::table('shop')->where('shop_id','=',$shop_id)->value('verified');
            if($verified != Data::DATA_DB_LAIFEI_SHOP_VERIFIED_SUCCESS){
                return $this->setReturnJson(-1,'当前店铺信息未审核通过，请重新编辑店铺并等待管理员审核');
            }

            // 检查当前店铺今天发了几单,超过3单不允许发了
            $order_count = DB::table('explore_order')
                ->where('shop_id','=',$shop_id)
                ->where('created_at','>=',date('Y-m-d').' 00:00:00')
                ->where('status','<>',Data::DATA_DB_EXPLORE_ORDER_STATUS_FAILED)
                ->count();
            if ($order_count >= 3) {
                return $this->setReturnJson(-1,'您的店铺今天已经发单3次，为保护您的店铺安全，请明天再来');
            }

            // 下载图片资源
            $shop_img = $all['shop_img']?? [];
            $images = [];
            $file_path = 'images/order/' . $shop_id;
            foreach ($shop_img as $key => $value){
                $images[] = File::saveMedia($value, $file_path);
            }
            $shop_img = implode(',',$images);
        } catch (\Exception $e) {
            Log::error(ExploreApplyController::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1, '申请失败，请重试或联系人工客服');
        }


        try{
            DB::beginTransaction();
            /**
             * 验证
             */
            // 验证剩余数量(加写锁)
            $remaining = DB::table('explore_remaining')
                ->where('we_id','=',$this->we_id)
                ->where('channel_id','=',$channel_id)
                ->lockForUpdate()
                ->first();
            $remaining = json_decode(json_encode($remaining),true);

            if(!$remaining['remaining_times'] || $remaining['remaining_times'] < $num){
                DB::rollBack();
                return $this->setReturnJson(-1,'探店剩余数量不足');
            }

            /**
             * 生成订单
             */
            // 扣除商户的探店剩余量
            DB::table('explore_remaining')
                ->where('r_id','=',$remaining['r_id'])
                ->update([
                    'remaining_times'=>$remaining['remaining_times']-$num,
                    'in_use_times'=>$remaining['in_use_times']+$num,
                ]);
            // 记录剩余探店数量日志
            DB::table('explore_remaining_log')->insert([
                'r_id'=>$remaining['r_id'],
                'action'=>Data::DATA_DB_EXPLORE_REMAINING_LOG_TYPE_CONSUME,
                'action_num'=>$num,
                'rest_num'=>$remaining['remaining_times']-$num,
                'in_use_num'=>$remaining['in_use_times']+$num,
            ]);
            // 生成订单
            $eo_id = DB::table('explore_order')->insertGetId([
                'we_id'=>$this->we_id,
                'shop_id'=>$shop_id,
                'channel_id'=>$channel_id,
                'start_date'=>$date[0],
                'end_date'=>$date[1],
                'offline'=>$offline,
                'total_num'=>$num,
                'remaining_num'=>$num,
                'remark'=>$remark,
                'shop_img'=>$shop_img,
            ]);
            // 记录申请日志
            DB::table('explore_order_log')->insert([
                'eo_id'=>$eo_id,
                'action'=>Data::DATA_DB_EXPLORE_ORDER_ACTION_APPLY,
                'we_id'=>$this->we_id
            ]);
            // 加入队列，48小时后刷新订单状态
            ExploreApplyJob::dispatch($eo_id)->delay(now()->addDays(2));
            DB::commit();
        } catch (\Exception $e){
            DB::rollBack();
            Log::error(ExploreApplyController::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1, '申请失败，请联系人工客服');
        }

        return $this->setReturnJson(0,'探店申请成功，请在我的进度查看');

    }

}
